<template>
  <v-container fluid tag="section">
    <v-row>
      <v-col sm="12" md="12">
        <v-card icon="mdi-clipboard-text" class="px-md-5 py-md-3 pa-xs-0 mt-0">
          <v-card-title>
            <v-row>
              <v-col cols="12" sm="12" md="3">
                <v-text-field v-model="search.name" label="名称"></v-text-field>
              </v-col>
              <v-col cols="12" sm="12" md="3">
                <v-menu
                  v-model="dateModal"
                  :close-on-content-click="false"
                  :nudge-right="40"
                  transition="scale-transition"
                  offset-y
                  min-width="auto"
                >
                  <template v-slot:activator="{ on, attrs }">
                    <v-text-field
                      v-model="search.opTime"
                      label="操作时间"
                      readonly
                      v-bind="attrs"
                      v-on="on"
                    ></v-text-field>
                  </template>
                  <v-date-picker
                    v-model="search.opTime"
                    range
                    dense
                    locale="zh-cn"
                    @input="dateModal = false"
                  ></v-date-picker>
                </v-menu>
              </v-col>
              <v-col cols="12" sm="12" md="3">
                <v-select
                  v-model="search.reqMethod"
                  :items="dataDicts.reqMethodDicts"
                  item-text="value"
                  item-value="value"
                  label="请求方式"
                ></v-select>
              </v-col>
              <v-col cols="12" sm="12" md="3">
                <v-select
                  v-model="search.success"
                  :items="dataDicts.yesOrNoDicts"
                  item-text="value"
                  item-value="code"
                  label="是否成功"
                ></v-select>
              </v-col>
              <v-col cols="12" sm="12" md="12" class="text-center">
                <v-btn
                  regular
                  color="primary"
                  @click="dataInitialize()"
                  class="mr-2"
                >
                  查 询
                </v-btn>
                <v-btn
                  regular
                  color="warning"
                  @click="clearChanged()"
                  class="ml-2"
                >
                  重 置
                </v-btn>
              </v-col>
            </v-row>
          </v-card-title>
          <v-card-text>
            <v-data-table
              v-model="selectedTableItems"
              :no-data-text="noDataText"
              :show-expand="showExpand"
              :single-expand="singleExpand"
              :show-select="showSelect"
              :single-select="singleSelect"
              :expanded.sync="expanded"
              :dense="dense"
              :headers="headers"
              :items="records"
              :options.sync="options"
              :multi-sort="multiSort"
              :server-items-length="total"
              :loading="loading"
              :item-key="itemKey"
              :loading-text="loadingText"
              :footer-props="footerProps"
              @update:options="dataInitialize()"
            >
              <template v-slot:expanded-item="{ headers, item }">
                <td :colspan="headers.length">返回结果： {{ item.result }}</td>
              </template>

              <template v-slot:top>
                <v-toolbar flat>
                  <v-toolbar-title class="d-none d-sm-flex">
                    {{ tableTitle }}
                  </v-toolbar-title>
                  <v-divider
                    class="mx-4 d-none d-sm-flex"
                    inset
                    vertical
                  ></v-divider>
                  <v-spacer></v-spacer>
                  <v-btn color="primary" dark @click="remove(-1)" class="mr-2">
                    批量删除
                  </v-btn>
                  <v-btn color="primary" dark @click="clearAllData()">
                    清空日志
                  </v-btn>
                  <v-dialog v-model="dialog" persistent max-width="600px">
                    <v-card>
                      <v-card-title class="text-left">
                        <span class="text-h3 font-weight-black text-left">
                          详情
                        </span>
                      </v-card-title>
                      <v-divider></v-divider>
                      <v-card-text class="pt-4">
                        <v-row>
                          <v-col cols="6" class="pl-5 pb-0">
                            <div class="text-h4 font-weight-bold">方法名</div>
                            <v-text-field
                              v-model="editedItem.methodName"
                              dense
                              readonly
                            ></v-text-field>
                          </v-col>
                          <v-col cols="6" class="pl-5 pb-0">
                            <div class="text-h4 font-weight-bold">地址</div>
                            <v-text-field
                              v-model="editedItem.location"
                              dense
                              readonly
                            ></v-text-field>
                          </v-col>
                          <v-col cols="6" class="pb-0">
                            <div class="text-h4 font-weight-bold">浏览器</div>
                            <v-text-field
                              v-model="editedItem.browser"
                              dense
                              readonly
                            ></v-text-field>
                          </v-col>
                          <v-col cols="6" class="pb-0">
                            <div class="text-h4 font-weight-bold">操作系统</div>
                            <v-text-field
                              v-model="editedItem.os"
                              dense
                              readonly
                            ></v-text-field>
                          </v-col>
                          <v-col cols="6" class="pb-0">
                            <div class="text-h4 font-weight-bold">类名</div>
                            <v-textarea
                              counter
                              v-model="editedItem.className"
                              dense
                              readonly
                            ></v-textarea>
                          </v-col>
                          <v-col cols="6" class="pb-0">
                            <div class="text-h4 font-weight-bold">具体消息</div>
                            <v-textarea
                              counter
                              v-model="editedItem.message"
                              dense
                              readonly
                            ></v-textarea>
                          </v-col>
                          <v-col cols="6" class="pb-0">
                            <div class="text-h4 font-weight-bold">请求参数</div>
                            <v-textarea
                              counter
                              v-model="editedItem.param"
                              dense
                              readonly
                            ></v-textarea>
                          </v-col>
                          <v-col cols="6" class="pb-0">
                            <div class="text-h4 font-weight-bold">返回结果</div>
                            <v-textarea
                              counter
                              v-model="editedItem.result"
                              dense
                              readonly
                            ></v-textarea>
                          </v-col>
                        </v-row>
                      </v-card-text>
                      <v-card-actions>
                        <v-spacer></v-spacer>
                        <v-btn text @click="close()" color="darken-1">
                          关闭
                        </v-btn>
                      </v-card-actions>
                    </v-card>
                  </v-dialog>
                </v-toolbar>
              </template>

              <template v-slot:[`item.success`]="{ item }">
                <v-chip :color="getColor(item.success)" dark>
                  {{ successFilter(item.success) }}
                </v-chip>
              </template>
              <template v-slot:[`item.actions`]="{ item }">
                <v-icon small @click="editItem(item)" title="详情" class="mr-2">
                  mdi-details
                </v-icon>
                <v-icon small @click="remove(item)" title="删除">
                  mdi-delete
                </v-icon>
              </template>
              <template v-slot:no-data>
                <v-btn small color="primary" @click="dataInitialize()">
                  刷新
                </v-btn>
              </template>
            </v-data-table>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
export default {
  name: "ExLogIndex",

  data: () => ({
    dense: false, //是否紧凑（降低行高）
    noDataText: "暂无任何数据", //没有数据时显示的内容
    loading: true, //开启加载条
    loadingText: "数据加载中...请稍候！", //加载条内容
    footerProps: {
      "items-per-page-options": [10, 20, 50, 100], //自定义每页行数的下拉框  -1 代表全部
      "items-per-page-text": "每页行数",
      //"items-per-page-all-text": "全部",
    },
    multiSort: true, //多列排序
    records: [], //数据
    total: 0, //数据总条数
    showExpand: true, //会在每个默认行上渲染一个展开图标
    singleExpand: true, //能同时展开多行还是只能展开一行
    showSelect: true, //将在默认表头中渲染一个复选框以切换所有行是否被选择，同时也为每个默认行渲染一个复选
    singleSelect: false, //指定能同时选择多行还是只能选择一行
    expanded: [], //展开行的内容

    //日期时间组件相关
    dateModal: false,
    itemKey: "id", //行项需要一个唯一的键属性才能展开。 默认值是id，但是你可以使用item-key prop来指定一个不同的item属性。
    tableTitle: "操作日志列表",
    //查询条件
    search: {
      name: "",
      reqMethod: "",
      success: "",
      opTime: [],
    },
    options: {
      page: 1, //当前页码
      itemsPerPage: 10, //每页多少条
      pageStart: 1, //起始页码
      pageStop: 1, //终止页码
      sortBy: ["opTime", "id"], //排序列
      sortDesc: [false, false], //排序列是否倒叙
    },
    headers: [
      {
        text: "序号", //标头
        align: "start", //所在位置
        sortable: true, //排序方式
        value: "id", //数据对应的字段名
      },
      { text: "请求方式", sortable: false, value: "reqMethod" },
      { text: "执行结果", sortable: false, value: "success" },
      { text: "IP", sortable: false, value: "ip" },
      { text: "请求地址", sortable: false, value: "url" },
      { text: "操作时间", sortable: true, value: "opTime" },
      { text: "操作人", sortable: false, value: "name" },
      { text: "操作人账户", sortable: false, value: "account" },
      { text: "", value: "data-table-expand" }, //可展开列
      { text: "详情", value: "actions", sortable: false },
    ],
    selectedTableItems: [], //选中的表格项
    // 表格弹框相关
    dialog: false,
    editedIndex: -1,
    editedItem: {
      id: 0,
      account: "",
      name: "",
      success: "",
      message: "",
      ip: "",
      location: "",
      browser: "",
      os: "",
      url: "",
      className: "",
      methodName: "",
      reqMethod: "",
      param: "",
      result: "",
      elapsedTime: "",
      opTime: "",
    },
    defaultItem: {
      id: 0,
      account: "",
      name: "",
      success: "",
      message: "",
      ip: "",
      location: "",
      browser: "",
      os: "",
      url: "",
      className: "",
      methodName: "",
      reqMethod: "",
      param: "",
      result: "",
      elapsedTime: "",
      opTime: "",
    },
    dataDicts: {
      reqMethodDicts: [],
      yesOrNoDicts: [],
    },
  }),
  created() {
    this.setDictDatas();
  },
  methods: {
    /**
     * 清空查询条件
     */
    clearChanged() {
      this.search.name = "";
      this.search.reqMethod = "";
      this.search.success = "";
      this.search.opTime = [];
    },
    /**
     * 数据初始化
     */
    dataInitialize() {
      var that = this;
      that.loading = true;
      that.request
        .post("/api/logOp/page", {
          page: that.options.page,
          itemsPerPage: that.options.itemsPerPage,
          sortBy: that.options.sortBy,
          sortDesc: that.options.sortDesc,
          // 查询条件
          name: that.search.name,
          reqMethod: that.search.reqMethod,
          success: that.search.success,
          opTime: that.search.opTime,
        })
        .then((res) => {
          that.records = res.data.records;
          that.total = res.data.total;
          that.loading = false;
        })
        .catch((error) => {
          console.log(error);
          that.loading = false;
        });
    },
    /**
     * 数据删除
     */
    dataDelete(ids) {
      var that = this;
      that.request
        .post("/api/logOp/removeBatchByIds", ids)
        .then((res) => {
          that.$dialog.notify.success("删除成功！", {
            timeout: 2000,
          });
          setTimeout(() => {
            that.dataInitialize();
          }, 2000);
        });
    },
    clearAll() {
      var that = this;
      that.request
        .post("/api/logOp/clearAll")
        .then((res) => {
          that.$dialog.notify.success(res.msg, {
            timeout: 2000,
          });
          setTimeout(() => {
            that.dataInitialize();
          }, 2000);
        });
    },
    /**
     * 设置字典数据
     */
    setDictDatas(text) {
      var that = this;
      that.request
        .get("/api/dictType/dropDown", {
          code: "request_type",
        })
        .then((res) => {
          that.dataDicts.reqMethodDicts = res.data;
        });
      that.request
        .get("/api/dictType/dropDown", {
          code: "yes_or_no2",
        })
        .then((res) => {
          that.dataDicts.yesOrNoDicts = res.data;
        });
    },
    /**
     * 成功状态过滤
     */
    successFilter(success) {
      const values = this.dataDicts.yesOrNoDicts.filter(
        (item) => item.code == success
      );
      if (values.length > 0) {
        return values[0].value;
      }
    },
    /**
     * 根据状态获取颜色
     */
    getColor(success) {
      return success == 0 ? "green" : "red";
    },
    /**
     * 清空所有数据
     */
    clearAllData() {
      var that = this;
      that.$dialog.confirm({
        text: "确定要清空所有数据?",
        title: "警告",
        icon: "mdi-alert-circle",
        actions: [
          {
            text: "取消",
            key: false,
          },
          {
            text: "确定",
            color: "primary",
            key: true,
            handler: function () {
              that.clearAll();
            },
          },
        ],
      });
    },
    /**
     * 删除项
     */
    remove(dataItem) {
      var that = this,
        ids = [];
      if (dataItem == -1) {
        // 批量删除
        var items = that.selectedTableItems;
        if (items == undefined || items == null || items.length == 0) {
          this.$dialog.notify.warning("请选择要删除的数据项！", {
            position: "top-right",
            timeout: 3000,
          });
          return;
        }
        ids = items.map((item) => {
          return item.id;
        });
      } else {
        ids.push(dataItem.id);
      }
      that.$dialog.confirm({
        text: "确定要删除该项数据吗?",
        title: "警告",
        icon: "mdi-alert-circle",
        actions: [
          {
            text: "取消",
            key: false,
          },
          {
            text: "确定",
            color: "primary",
            key: true,
            handler: function () {
              that.dataDelete(ids);
            },
          },
        ],
      });
    },
    /**
     * 修改项
     */
    editItem(item) {
      this.editedIndex = this.records.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.dialog = true;
    },
    /**
     * 关闭编辑弹框
     */
    close() {
      this.dialog = false;
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem);
        this.editedIndex = -1;
      });
    },
  },
  // watch:function(new,old){}，
  // 监听data中数据的变化，两个参数，一个返回新值，一个返回旧值
  watch: {
    dialog(val) {
      val || this.close();
    },
  },
};
</script>
